package com.hui.demo.mail.impl;

import com.hui.demo.model.User;
import com.hui.demo.mail.SendJunkMailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 发送用户邮件服务实现类
 * @author ziv
 * @date 2018-12-20
 */
@Service
public class SendJunkMailServiceImpl implements SendJunkMailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 日志对象
     */
    private static final Logger logger = LogManager.getLogger(SendJunkMailServiceImpl.class);

    @Override
    public boolean sendJunkMail (List<User> userList) {
        if (userList != null && userList.size() > 0) {
            try {
                for (User user: userList) {
                    MimeMessage mimeMessage = this.mailSender.createMimeMessage();
                    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
                    // 邮件发送方
                    messageHelper.setFrom(from);
                    logger.info(from);
                    // 邮件主题
                    messageHelper.setSubject("审核结果");
                    // 邮件接收方
                    messageHelper.setTo("2679326023@qq.com");
                    // 邮件内容
                    messageHelper.setText(user.getUserName() + "你的申请审核通过 ");
                    // 发送邮件
                    this.mailSender.send(mimeMessage);
                }
            } catch (Exception e) {
                logger.error("sendJunkmail error and userList=%s", userList);
                logger.error(e);
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}
